from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated, AllowAny
from django.core.exceptions import ValidationError

from .models import User, UserAddress
from .serializers import (
    UserSerializer, UserProfileSerializer, WechatLoginSerializer,
    UserAddressSerializer, UserAddressCreateSerializer
)
from .services import WechatService, UserService, UserVipService
from common.utils.response import APIResponse


class UserViewSet(viewsets.ModelViewSet):
    """用户视图集"""
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = [IsAuthenticated]

    def get_permissions(self):
        """根据action设置权限"""
        if self.action in ['wechat_login']:
            return [AllowAny()]
        return super().get_permissions()

    @action(detail=False, methods=['post'], permission_classes=[AllowAny])
    def wechat_login(self, request):
        """微信登录"""
        try:
            serializer = WechatLoginSerializer(data=request.data)
            if serializer.is_valid():
                code = serializer.validated_data['code']
                user_info = request.data.get('userInfo')
                
                user = WechatService.login_or_register(code, user_info)
                
                # 这里应该生成JWT token或session
                # 简化处理，直接返回用户信息
                user_serializer = UserSerializer(user)
                return APIResponse.success(
                    data={
                        'user': user_serializer.data,
                        'token': f'user_{user.id}'  # 简化的token
                    },
                    message="登录成功"
                )
            return APIResponse.error(message="数据验证失败", data=serializer.errors)
        except ValidationError as e:
            return APIResponse.error(message=str(e))
        except Exception as e:
            return APIResponse.error(message=f"登录失败: {str(e)}")

    @action(detail=False, methods=['get'], permission_classes=[AllowAny])
    def profile(self, request):
        """获取用户资料"""
        try:
            # 直接使用中间件设置的用户信息
            if not request.user or not hasattr(request.user, 'id'):
                return APIResponse.error(message="用户未登录", code=401)
            
            # 直接使用request.user，不通过UserService
            serializer = UserSerializer(request.user)
            return APIResponse.success(data=serializer.data, message="获取用户资料成功")
        except Exception as e:
            return APIResponse.error(message=f"获取用户资料失败: {str(e)}")

    @action(detail=False, methods=['put'], permission_classes=[AllowAny])
    def update_profile(self, request):
        """更新用户资料"""
        try:
            # 从请求中获取用户ID（临时方案）
            user_id = request.data.get('user_id')
            if not user_id:
                return APIResponse.error(message="缺少用户ID")
                
            serializer = UserProfileSerializer(data=request.data, partial=True)
            if serializer.is_valid():
                user = UserService.update_user_profile(
                    user_id, 
                    serializer.validated_data
                )
                return APIResponse.success(
                    data=UserSerializer(user).data,
                    message="更新用户资料成功"
                )
            return APIResponse.error(message="数据验证失败", data=serializer.errors)
        except ValidationError as e:
            return APIResponse.error(message=str(e))
        except Exception as e:
            return APIResponse.error(message=f"更新用户资料失败: {str(e)}")

    @action(detail=False, methods=['get'])
    def vip_status(self, request):
        """获取VIP状态"""
        try:
            is_vip = UserVipService.check_vip_status(request.user.id)
            user = User.objects.get(id=request.user.id)
            return APIResponse.success(
                data={
                    'is_vip': is_vip,
                    'vip_expire_time': user.vip_expire_time
                },
                message="获取VIP状态成功"
            )
        except Exception as e:
            return APIResponse.error(message=f"获取VIP状态失败: {str(e)}")


class UserAddressViewSet(viewsets.ModelViewSet):
    """用户地址视图集"""
    serializer_class = UserAddressSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return UserAddress.objects.filter(user=self.request.user)

    def get_serializer_class(self):
        if self.action == 'create':
            return UserAddressCreateSerializer
        return UserAddressSerializer

    def list(self, request, *args, **kwargs):
        """获取用户地址列表"""
        try:
            addresses = UserService.get_user_addresses(request.user.id)
            serializer = self.get_serializer(addresses, many=True)
            return APIResponse.success(data=serializer.data, message="获取地址列表成功")
        except Exception as e:
            return APIResponse.error(message=f"获取地址列表失败: {str(e)}")

    def create(self, request, *args, **kwargs):
        """创建用户地址"""
        try:
            serializer = self.get_serializer(data=request.data)
            if serializer.is_valid():
                address = UserService.create_user_address(
                    request.user.id,
                    serializer.validated_data
                )
                return APIResponse.success(
                    data=UserAddressSerializer(address).data,
                    message="创建地址成功"
                )
            return APIResponse.error(message="数据验证失败", data=serializer.errors)
        except ValidationError as e:
            return APIResponse.error(message=str(e))
        except Exception as e:
            return APIResponse.error(message=f"创建地址失败: {str(e)}")

    def update(self, request, *args, **kwargs):
        """更新用户地址"""
        try:
            serializer = self.get_serializer(data=request.data, partial=True)
            if serializer.is_valid():
                address = UserService.update_user_address(
                    kwargs['pk'],
                    request.user.id,
                    serializer.validated_data
                )
                return APIResponse.success(
                    data=UserAddressSerializer(address).data,
                    message="更新地址成功"
                )
            return APIResponse.error(message="数据验证失败", data=serializer.errors)
        except ValidationError as e:
            return APIResponse.error(message=str(e))
        except Exception as e:
            return APIResponse.error(message=f"更新地址失败: {str(e)}")

    def destroy(self, request, *args, **kwargs):
        """删除用户地址"""
        try:
            UserService.delete_user_address(kwargs['pk'], request.user.id)
            return APIResponse.success(message="删除地址成功")
        except ValidationError as e:
            return APIResponse.error(message=str(e))
        except Exception as e:
            return APIResponse.error(message=f"删除地址失败: {str(e)}")

    @action(detail=False, methods=['get'])
    def default(self, request):
        """获取默认地址"""
        try:
            address = UserService.get_default_address(request.user.id)
            if address:
                serializer = self.get_serializer(address)
                return APIResponse.success(data=serializer.data, message="获取默认地址成功")
            return APIResponse.success(data=None, message="暂无默认地址")
        except Exception as e:
            return APIResponse.error(message=f"获取默认地址失败: {str(e)}")

    @action(detail=True, methods=['post'])
    def set_default(self, request, pk=None):
        """设置默认地址"""
        try:
            address = UserService.set_default_address(pk, request.user.id)
            return APIResponse.success(
                data=UserAddressSerializer(address).data,
                message="设置默认地址成功"
            )
        except ValidationError as e:
            return APIResponse.error(message=str(e))
        except Exception as e:
            return APIResponse.error(message=f"设置默认地址失败: {str(e)}")